package Askgene::Queue;

use warnings;
use strict;

use TheSchwartz;
use TheSchwartz::Job;
use DateTime;
use Askgene::Queue::Worker;
use File::Copy  ();
use Time::HiRes ();
use Moose;
use MooseX::Params::Validate;

has work_dir => ( isa => 'Path::Class::Dir', is => 'rw', required => 1 );
has connection_info => (
    isa      => 'ArrayRef',
    is       => 'rw',
    required => 1,
    trigger  => sub { shift->_clear_client }
);
has _client => ( isa => 'TheSchwartz', is => 'rw', lazy_build => 1 );

sub _build__client {
    my ($self) = @_;
    TheSchwartz->new( databases => $self->connection_info );
}

sub BUILD {

    # force client initialization
    shift->_client;
}

sub add_item {
    my ( $self, %args ) = validate(
        \@_,
        file      => { isa => 'Path::Class::File', required => 1 },
        filename  => { isa => 'Str', },
        move_file => {
            isa     => 'Bool',
            default => sub { 0 }
        }
    );

    my $file       = $args{file};
    my $filename   = $args{filename} || $file->basename;
    my $unique_key = Time::HiRes::time();
    $filename = $self->work_dir->file("${filename}_${unique_key}");
    if ( $args{move_file} ) {
        File::Copy::move( $file, $filename )
          or die qq{error moving $file to $filename: $!};
    }
    else {
        File::Copy::copy( $file, $filename )
          or die qq{error copying $file to $filename: $!};
    }
    my $job =
      TheSchwartz::Job->new_from_array( 'Askgene::Queue::Worker',
        { file => $filename->basename } );
    $self->_client->insert($job);
    return $job;
}

no Moose;

1;
